/**
 * @(#)EnumIntegerTypeHandler.java, 2018/2/2.
 * <p/>
 * Copyright 2018 Kerr Wang, Inc. All rights reserved.
 * KERRWANG PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */
package org.wangzx.exercise.enums;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author hzwangzuxiang(ahscwzx@163.com)
 */
public class EnumIntegerTypeHandler<E extends EnumIntegerInterface<E>>
        extends BaseTypeHandler<E> {

    private Class<E> type;

    private final E[] enums;

    public EnumIntegerTypeHandler(Class<E> type) {
        this.type = type;
        this.enums = type.getEnumConstants();
        if (this.enums == null) {
            throw new IllegalArgumentException(
                    type.getSimpleName() + " does not represent an enum type.");
        }
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter,
                                    JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        int i = rs.getInt(columnName);
        if (rs.wasNull()) {
            return null;
        }

        for (E e: enums) {
            if (e.getValue() == i)
                return e;
        }
        throw new IllegalArgumentException("Cannot convert " + i + " to "
                + type.getSimpleName() + " by ordinal value.", null);
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        int i = rs.getInt(columnIndex);
        if (rs.wasNull()) {
            return null;
        }

        for (E e: enums) {
            if (e.getValue() == i)
                return e;
        }
        throw new IllegalArgumentException("Cannot convert " + i + " to "
                + type.getSimpleName() + " by ordinal value.", null);
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        int i = cs.getInt(columnIndex);
        if (cs.wasNull()) {
            return null;
        }
        for (E e: enums) {
            if (e.getValue() == i)
                return e;
        }
        throw new IllegalArgumentException("Cannot convert " + i + " to "
                + type.getSimpleName() + " by ordinal value.", null);
    }

}
